package com.heking.cameralib;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.zhoug.camera.ui.ocr.CameraOcrImageActivity;
import com.zhoug.camera.ui.ocr.OcrType;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = ">>>MainActivity";
    private Button mBtn1;
    private ImageView mImageView;
    private static final int REQUEST_CODE_CAMERA=2012;
    private static final int REQUEST_CODE_PERMISSION=101;
    private String[] permissions=new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViews();
        mBtn1.setOnClickListener(v->{
            File externalCacheDir = getExternalCacheDir();
            File file=new File(externalCacheDir,System.currentTimeMillis()+".jpg");
            CameraOcrImageActivity.startForResult(this,REQUEST_CODE_CAMERA, OcrType.BUSINESS_LICENSE,file.getPath());
        });

       if(!checkAllPermissions()){
           ActivityCompat.requestPermissions(this,permissions,REQUEST_CODE_PERMISSION);
       }
    }

    private void findViews() {
        mBtn1 = findViewById(R.id.btn1);
        mImageView = findViewById(R.id.imageView);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode==REQUEST_CODE_CAMERA && resultCode==RESULT_OK && data!=null){
            String path = data.getStringExtra(CameraOcrImageActivity.EXTRA_PATH);
            Log.d(TAG, "onActivityResult:path="+path);
            if(path!=null && new File(path).exists()){
                Toast.makeText(this, "拍照成功", Toast.LENGTH_SHORT).show();
                mImageView.setImageURI(Uri.fromFile(new File(path)));
            }else{
                Toast.makeText(this, "拍照失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean checkAllPermissions(){
        for(String per:permissions){
            if(ContextCompat.checkSelfPermission(this,per)!= PackageManager.PERMISSION_GRANTED){
                return false;
            }
        }
        return true;
    }
}